package com.innovation.ic.im.end.base.thread.data;

import com.innovation.ic.im.end.base.model.im_erp9.ChatPair;
import com.innovation.ic.im.end.base.model.im_erp9.TempChatPair;
import com.innovation.ic.im.end.base.service.im_erp9.ChatPairService;
import com.innovation.ic.im.end.base.service.im_erp9.TempChatPairService;
import com.innovation.ic.im.end.base.thread.AbstractThread;

/**
 * 向表chat_pair中插入数据
 */
public class SaveChatPairThread extends AbstractThread implements Runnable {
    private String fromUserAccount;
    private String toUserAccount;
    private Integer code;

    public SaveChatPairThread() {}

    public SaveChatPairThread(String fromUserAccount, String toUserAccount, Integer code, ChatPairService chatPairService, TempChatPairService tempChatPairService) {
        this.fromUserAccount = fromUserAccount;
        this.toUserAccount = toUserAccount;
        this.code = code;
        this.chatPairService = chatPairService;
        this.tempChatPairService = tempChatPairService;
    }

    @Override
    public void run() {
        ChatPair chatPairOne = new ChatPair();
        chatPairOne.setFromUserAccount(fromUserAccount);
        chatPairOne.setToUserAccount(toUserAccount);
        chatPairOne.setCode(code);
        // 处理备份数据
        chatPairOne = handleTempData(chatPairOne, fromUserAccount, toUserAccount);
        chatPairService.saveChatPair(chatPairOne);
        ChatPair chatPairTwo = new ChatPair();
        chatPairTwo.setFromUserAccount(toUserAccount);
        chatPairTwo.setToUserAccount(fromUserAccount);
        chatPairTwo.setCode(code);
        // 处理备份数据
        chatPairTwo = handleTempData(chatPairTwo, toUserAccount, fromUserAccount);
        chatPairService.saveChatPair(chatPairTwo);
    }

    /**
     * 处理备份数据
     * @param fromUserAccount
     * @param toUserAccount
     */
    private ChatPair handleTempData(ChatPair chatPair, String fromUserAccount, String toUserAccount) {
        // 查询temp_chat_pair表中是否有历史数据，有的话将值存储到当前类
        TempChatPair tempChatPair = tempChatPairService.getTempChatPairData(fromUserAccount, toUserAccount);
        if(tempChatPair != null){
            // 置顶时间
            if(tempChatPair.getToppingTime() != null){
                chatPair.setToppingTime(tempChatPair.getToppingTime());
            }

            // 最近联系时间
            if(tempChatPair.getLastContactTime() != null){
                chatPair.setLastContactTime(tempChatPair.getLastContactTime());
            }

            // 内容不可见时间
            if(tempChatPair.getContentInvisibleTime() != null){
                chatPair.setContentInvisibleTime(tempChatPair.getContentInvisibleTime());
            }
        }
        return chatPair;
    }
}
